<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    //
    protected $categories;

    public function __construct()
    {
        $this->categories = Category::orderBy('id', 'asc')->get();
    }

    public function create()
    {
        $cats = $this->categories;

        return view('category.index', compact('cats'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:60',
            'slug' => 'required|max:60',
            'weight' => 'required',
        ]);
        $cats = Category::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'weight' => $request->weight,
        ]);
        return redirect()->route('category.create');
    }

    public function update(Request $request, $id)
    {
        //验证数据
        $this->validate($request, [
            'name' => 'required|max:60',
            'slug' => 'required|max:60',
            'weight' => 'required|digits_between:0,99',
        ]);
        //返回当前分类
        $category = Category::findOrFail($id);

        //更新数据
        $category->update([
            'name' => $request->name,
            'slug' => $request->slug,
            'weight' => $request->weight,
        ]);
        session()->flash('success', '修改成功');
        return redirect()->route('category.create');
    }

    public function destroy($id)
    {
        $category = Category::findOrFail($id);
        $wordids = array();
        foreach ($category->words() as $word) {
            array_push($wordids, $word->id);
        }
        $category->words()->detach();
        $category->delete();
        return redirect()->route('category.create');
    }
}
